<?php

class WordController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','import'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Word;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Word']))
		{
			$model->attributes=$_POST['Word'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->wid));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Word']))
		{
			$model->attributes=$_POST['Word'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->wid));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Word');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Word('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Word']))
			$model->attributes=$_GET['Word'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	public function actionImport(){
		$model=new Word;
	
   		if(isset($_FILES['filee']) && $_FILES['filee']['error']==0)
		{
			//spl_autoload_unregister(array('YiiBase','autoload'));  //注销YII的自动加载，采用手动导入，PHPexcel有自己的加载功能
		    include_once(dirname(dirname(__FILE__)).'\extensions\Excel\reader.php'); 
			//spl_autoload_register(array('YiiBase','autoload'));                                                      //重新启用YII的自动载入
			$data = new Spreadsheet_Excel_Reader();
			$data->setOutputEncoding('UTF-8');
			$data->read($_FILES['filee']['tmp_name']);   
			error_reporting(E_ALL ^ E_NOTICE);

			for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
				/*
				 *  'phonetic' => 'Phonetic',
					'chinese' => 'Chinese',
					'sid' => 'Speech',
					'sentence' => 'Sentence',
					'sound' => 'Sound file',
					'slow_sound' => 'Slow sound file',
					'cid' => 'Catalog',
					'sentence_sound' => 'Sentence sound file',
				 * */
			    $word = new Word;
				$word->spell = $data->sheets[0]['cells'][$i][1];
				$word->phonetic = ($data->sheets[0]['cells'][$i][2] != null)?mysql_escape_string($data->sheets[0]['cells'][$i][2]):"";
				$word->sid = $this->returnSpeech($data->sheets[0]['cells'][$i][3]);
				$word->chinese = mysql_escape_string($data->sheets[0]['cells'][$i][4]);
				$word->sentence = mysql_escape_string($data->sheets[0]['cells'][$i][5]);
				$word->sound = $data->sheets[0]['cells'][$i][6];
				$word->cid = $_POST['cid'];
				//$word->slow_sound = $data->sheets[0]['cells'][$i][8];
				//$word->sentence_cid = $data->sheets[0]['cells'][$i][9];
				$word->save();
			}
			$this->redirect(array('admin'));     
        }
		$this->render('import',array(
			'model'=>$model,
		));
	}
	
	private function returnSpeech($speech){
		$s = Speech::model()->find('speech=:speech',array(':speech'=>$speech));
		$sid = $s->sid;
		return $sid;
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Word::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='word-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
